package com.dms.modules.payment.controller;

import com.dms.common.api.ApiResponse;
import com.dms.common.security.SecurityUtils;
import com.dms.common.exception.BusinessException;
import com.dms.modules.order.service.OrderService;
import com.dms.modules.payment.dto.PaymentDTO;
import com.dms.modules.payment.service.PaymentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

/**
 * 支付控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/payment")
@Api(tags = "支付管理")
@RequiredArgsConstructor
@PreAuthorize("hasRole('USER')")
public class PaymentController {

    private final PaymentService paymentService;
    private final OrderService orderService;

    /**
     * 创建支付订单
     */
    @PostMapping("/create")
    @ApiOperation(value = "创建支付订单", notes = "为一个或多个订单创建支付订单，在订单提交后调用此接口进行支付")
    public ApiResponse<String> createPayment(@RequestBody @Valid PaymentDTO paymentDTO) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            String paymentUrl = paymentService.createPayment(userId, paymentDTO);
            return ApiResponse.success(paymentUrl);
        } catch (BusinessException e) {
            log.warn("创建支付订单失败: {}", e.getMessage());
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error("创建支付订单失败", e);
            return ApiResponse.error("创建支付订单失败");
        }
    }

    /**
     * 查询支付状态
     */
    @GetMapping("/status/{orderId}")
    @ApiOperation("查询支付状态")
    public ApiResponse<Boolean> queryPaymentStatus(@PathVariable @NotNull Long orderId) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            boolean paid = paymentService.queryPaymentStatus(userId, orderId);
            return ApiResponse.success(paid);
        } catch (BusinessException e) {
            log.warn("查询支付状态失败: {}", e.getMessage());
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error("查询支付状态失败", e);
            return ApiResponse.error("查询支付状态失败");
        }
    }

    /**
     * 支付回调处理
     */
    @PostMapping("/notify/{paymentType}")
    @ApiOperation(value = "支付回调处理", notes = "处理支付平台的异步通知，支持单个订单和合并订单支付")
    public String handlePaymentNotify(
            @PathVariable @NotNull String paymentType,
            @RequestParam String orderNo,
            @RequestParam String paymentNo,
            @RequestParam boolean success) {
        try {
            return paymentService.handlePaymentCallback(paymentType, orderNo, paymentNo, success) ? "success" : "fail";
        } catch (Exception e) {
            log.error("处理支付回调失败", e);
            return "fail";
        }
    }
} 